package Servlets;

import main.ServerGlobals;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import protocol.HTTPRequest;
import protocol.HTTPResponse;
import protocol.Headers;
import SQL.SQLLiteHandler;

public class Send extends Servlet {

	private boolean isError701(HTTPRequest args, ServerGlobals serverGlobalse) {
		String type = (args.getfHttpmsg().toJSONObject()).get("Type")
				.toString();
		if (type.equals("Group")) {
			JSONArray res = this.fSQLLiteHandler.Query("select * from "
					+ WhatsAppConstatnts.TABLE_GROUPS
					+ " where "
					+ WhatsAppConstatnts.GROUP_NAME
					+ "='"
					+ SQLLiteHandler.clean(args.getfHttpmsg().toJSONObject()
							.get("Target").toString()) + "'");
			if (res.size() == 0) {
				return true;
			}
		}

		if (type.equals("Direct")) {
			JSONArray res = this.fSQLLiteHandler.Query("select * from "
					+ WhatsAppConstatnts.TABLE_USERS
					+ " where "
					+ WhatsAppConstatnts.PHONE
					+ "='"
					+ SQLLiteHandler.clean(args.getfHttpmsg().toJSONObject()
							.get("Target").toString()) + "'");
			if (res.size() == 0) {
				return true;
			}
		}
		return false;
	}

	private boolean isError836(HTTPRequest args, ServerGlobals serverGlobals) {
		String type = (args.getfHttpmsg().toJSONObject()).get("Type")
				.toString();
		if (!type.equals("Group") && !type.equals("Direct")) {
			return true;
		}
		return false;
	}

	private void sendMSGToGroup(HTTPRequest args, ServerGlobals serverGlobals) {
		String type = (args.getfHttpmsg().toJSONObject()).get("Type")
				.toString();
		if (type.equals("Group")) {
			JSONArray rs = this.fSQLLiteHandler.Query("select "
					+ WhatsAppConstatnts.USERNAME
					+ " from "
					+ WhatsAppConstatnts.TABLE_GROUPS
					+ " WHERE "
					+ WhatsAppConstatnts.GROUP_NAME
					+ "='"
					+ SQLLiteHandler.clean((args.getfHttpmsg().toJSONObject())
							.get("Target").toString()) + "'");
			for (int i = 0; i < rs.size(); i++) {
				this.fSQLLiteHandler.Query("INSERT INTO "
						+ WhatsAppConstatnts.TABLE_MESSAGES
						+ " ("
						+ WhatsAppConstatnts.USERNAME
						+ ","
						+ "Target,message,"
						+ WhatsAppConstatnts.GROUP_NAME
						+ ") VALUES ('"
						+ SQLLiteHandler.clean(serverGlobals
								.getSession(this.getSessionId(args))
								.get(WhatsAppConstatnts.USERNAME).toString())
						+ "','"
						+ SQLLiteHandler.clean(((JSONObject) rs.get(i)).get(
								WhatsAppConstatnts.USERNAME).toString())
						+ "','"
						+ SQLLiteHandler.clean(args.getfHttpmsg()
								.toJSONObject().get("Content").toString())
						+ "','"
						+ SQLLiteHandler.clean((args.getfHttpmsg()
								.toJSONObject()).get("Target").toString())
						+ "')");
			}
		}
	}

	private void sendMSGToUser(HTTPRequest args, ServerGlobals serverGlobals) {
		String type = (args.getfHttpmsg().toJSONObject()).get("Type")
				.toString();
		if (type.equals("Direct")) {
			JSONArray rs = this.fSQLLiteHandler.Query("select "
					+ WhatsAppConstatnts.USERNAME
					+ " from "
					+ WhatsAppConstatnts.TABLE_USERS
					+ " WHERE "
					+ WhatsAppConstatnts.PHONE
					+ "='"
					+ SQLLiteHandler.clean((args.getfHttpmsg().toJSONObject())
							.get("Target").toString()) + "'");
			for (int i = 0; i < rs.size(); i++) {
				this.fSQLLiteHandler.Query("INSERT INTO "
						+ WhatsAppConstatnts.TABLE_MESSAGES
						+ " ("
						+ WhatsAppConstatnts.USERNAME
						+ ","
						+ "Target,message) VALUES ('"
						+ SQLLiteHandler.clean(serverGlobals
								.getSession(this.getSessionId(args))
								.get(WhatsAppConstatnts.USERNAME).toString())
						+ "','"
						+ SQLLiteHandler.clean(((JSONObject) rs.get(i)).get(
								WhatsAppConstatnts.USERNAME).toString())
						+ "','"
						+ SQLLiteHandler.clean(args.getfHttpmsg()
								.toJSONObject().get("Content").toString())
						+ "')");
			}
		}
	}

	@Override
	public HTTPResponse process(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		if (!this.isCorrectMethod(httpRequest, Headers.POST)) {
			return new HTTPResponse(Headers.STATUS_405, Headers.HTTP_VERSION,
					new JSONObject(), "", false);
		}
		if (!this.isAuthorized(httpRequest, serverGlobals)) {
			return new HTTPResponse(Headers.STATUS_403, Headers.HTTP_VERSION,
					new JSONObject(), "", false);
		}
		if (!this.areParametersRequiredSent(new String[] { "Type", "Target",
				"Content" }, httpRequest)) {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(), WhatsAppConstatnts.ERROR_711, false);
		}

		if (isError836(httpRequest, serverGlobals)) {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(), WhatsAppConstatnts.ERROR_836, false);
		}

		if (isError701(httpRequest, serverGlobals)) {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(), WhatsAppConstatnts.ERROR_771, false);
		}
		sendMSGToGroup(httpRequest, serverGlobals);
		sendMSGToUser(httpRequest, serverGlobals);
		return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
				new JSONObject(), "Message Sent!", false);
	}
}
